from tkinter import *
import os
import socket

'''
此模块提供端口测试功能
'''

class porttest():
    def __init__(self):
        pass

    def windowstwo(self,root):
        w = Toplevel(root)
        w.title('端口检查工具')
        w.geometry('610x200')
        w.geometry('+600+400')
        w.maxsize(width='610',height='200')

        #标签页，用于注释说明
        l1 = Label(w,text='检测目标端口是否开启',font='5')
        l1.grid(row=1,column=1,padx=5,pady=5)

        l2 = Label(w,text='目标ip',font='5',bg='yellow')  
        l2.grid(row=2,column=0,padx=5,pady=5)

        l21 = Label(w,text='端口号',font='5',bg='yellow')
        l21.grid(row=2,column=2,padx=5,pady=5)

        l3 = Label(w,text='结果',font='5',bg='yellow')
        l3.grid(row=3,column=0,padx=5,pady=5)

        #输入框:ip
        self.e1 = Entry(w)
        self.e1.grid(row=2,column=1,padx=5,pady=5)
        #输入框:port
        self.e2 = Entry(w)
        self.e2.grid(row=2,column=3,padx=5,pady=5)

        #开始按键
        b1 = Button(w,text='开始',font='5',bg='red',command=two.getresult)
        b1.grid(row=2,column=5,padx=5,pady=5)

        #输出框
        self.var=StringVar()
        self.e3 = Entry(w,textvariable=self.var)
        self.e3.grid(row=3,column=1,padx=5,pady=5)

        #退出按键
        # b2 = Button(w,text='退出',font='5',bg='red',command=quit)
        # b2.grid(row=3,column=5,padx=5,pady=5)

        w.mainloop()

    def getresult(self):
        #得到输入框中输入的值
        ip = self.e1.get()
        port = self.e2.get()
        port = int(port)
        
        # 根据ip的长度来判断是ipv4还是ipv6
        iplength = len(ip)
        if iplength < 20:
            sk = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
            sk.settimeout(2)
            try:
                sk.connect((ip,port))
                print('端口连接成功')
                self.var.set('端口连接成功')
            except:
                print('端口连接失败')
                self.var.set('端口连接失败')
        else:
            sk = socket.socket(socket.AF_INET6,socket.SOCK_STREAM)
            sk.settimeout(2)
            try:
                sk.connect((ip,port))
                print('端口连接成功')
                self.var.set('端口连接成功')
            except:
                print('端口连接失败')
                self.var.set('端口连接失败')

two = porttest()

#模块单独执行的时候，把下面的井号去掉即可
#two.windowstwo()
